package com.gy.api.pc.sys.authority.service.impl;

import com.gy.api.base.Type;
import com.gy.api.pc.sys.authority.dao.SysAuthorityDao;
import com.gy.api.pc.sys.authority.domain.po.SysAuthorityPO;
import com.gy.api.pc.sys.authority.domain.vo.*;
import com.gy.api.pc.sys.authority.service.ISysAuthorityService;
import com.gy.api.pc.sys.user.domain.po.SysUserPO;
import com.gy.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


@Service
@Transactional
@Slf4j
public class SysAuthorityServiceImpl implements ISysAuthorityService {
    @Autowired
    private SysAuthorityDao sysAuthorityDao;


    @Override
    public List<SysAuthorityTreeVO> getTreeList(SysAuthoritySearchVO searchVO) {
        List<SysAuthorityTreeVO> rList = new ArrayList<>();
        List<SysAuthorityTreeVO> list = sysAuthorityDao.getTreeList(searchVO);
        HashMap<String, SysAuthorityTreeVO> map = new HashMap<>();
        for (SysAuthorityTreeVO vo : list) {
            map.put(vo.getId(), vo);
        }
        for (SysAuthorityTreeVO vo : list) {
            if (vo.getParentId() == null) {
                continue;
            }
            if (vo.getParentId().equals("0")) {
                rList.add(vo);
            } else {
                SysAuthorityTreeVO parentVO = map.get(vo.getParentId());
                if (parentVO == null) {
                    rList.add(vo);
                    continue;
                }
                if (parentVO.getChildren() == null) {
                    parentVO.setChildren(new ArrayList<>());
                }
                parentVO.getChildren().add(vo);
            }
        }
        return rList;
    }

    @Override
    public List<SysAuthorityVO> getList(SysAuthoritySearchVO searchVO) {
        return sysAuthorityDao.getList(searchVO);
    }

    @Override
    public void update(SysAuthorityUpdateVO vo) {
        SysAuthorityPO po = sysAuthorityDao.selectByPrimaryKey(vo.getId());
        if(po==null){
            throw new BusinessException(Type.NOT_FOUND_ERROR.getCode(),  "信息不存在");
        }
        BeanUtils.copyProperties(vo, po);
        po.preUpdate();
        sysAuthorityDao.updateByPrimaryKeySelective(po);
    }

    @Override
    public void add(SysAuthorityAddVO vo) {
        SysAuthorityPO po = new SysAuthorityPO();
        BeanUtils.copyProperties(vo, po);
        po.preInsert();
        sysAuthorityDao.insertSelective(po);
    }

    @Override
    public void delete(String id) {
        SysAuthorityPO po = sysAuthorityDao.selectByPrimaryKey(id);
        if(po==null){
            throw new BusinessException(Type.NOT_FOUND_ERROR.getCode(),  "信息不存在");
        }
        sysAuthorityDao.deleteByPrimaryKey(id);
    }
}